<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./lib/lodash.min.js"></script>
</head>

<body>
  <script>
    // json方法：
    // const obj = {
    //   name: 'zp',
    //   age: 18,
    //   family: {
    //     son: 'lwj'
    //   }
    // }
    // const newObj = JSON.parse(JSON.stringify(obj))
    // newObj.name = 'lzt'
    // newObj.family.son = 'lzt'
    // console.log(newObj)
    // console.log(obj)
    // console.log(obj.family === newObj.family)//false


    // 第三方库： lodash库
    // const obj = {
    //   name: 'zp',
    //   age: 18,
    //   family: {
    //     son: 'lwj'
    //   }
    // }
    // const newObj = _.cloneDeep(obj)
    // console.log(newObj)
    // console.log(obj)
    // console.log(obj === newObj)//false
    // console.log(obj.family === newObj.family)//false


    // 封装函数递归拷贝：
    const obj = {
      name: 'zp',
      age: 18,
      family: {
        son: 'lwj'
      }
    }

    function replica(obj) {
      if (typeof obj !== 'object' || obj === null) {
        return obj
      }
      const newObj = Array.isArray(obj) ? [] : {}
      for (const key in obj) {
        // newObj[key] = obj[key]
        newObj[key] = replica(obj[key])// 实现深拷贝关键代码
      }
      return newObj
    }
    const newObj = replica(obj)
    console.log(newObj)
    console.log(obj)
    console.log(obj === newObj)//false
    console.log(obj.family === newObj.family)//false
  </script>
</body>

</html>